from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
import jwt
from jwt import exceptions
from rest_framework.response import Response
from django.conf import settings


class JwtQueryParamsAuthentication(BaseAuthentication):
    def authenticate(self, request):
        # 获取token并判断token的合法性
        token = request._request.GET.get('token')
        # token_obj = models.UserToken.objects.filter(token=token).first()
        # 1. 切割
        # 2. 解密第二段
        # 3. 验证第三段

        salt = settings.SECRET_KEY
        payload = None
        msg = None
        try:
            payload = jwt.decode(token, salt, algorithms='HS256')
        except exceptions.ExpiredSignatureError:
            msg = ('token已失效')
            raise AuthenticationFailed({"code":"1003","error":msg})
        except jwt.DecodeError:
            msg = ('token认证失败,请在url加上?token = ****')
            raise AuthenticationFailed({"code":"1003","error":msg})
        except jwt.InvalidTokenError:
            msg = ('非法的token')
            raise AuthenticationFailed({"code": "1003", "error": msg})
        return (payload,token)

        # 三种操作
        #  1. 抛出异常，后续不再执行
        #  2.return 一个元组(1,2)，认证通过，在视图中调用request.user则为第一个值，request.auth则取第二个
        #  3.None